﻿using AutoMapper;
using B.Auth.APi.Application.Command.Leaves;
using B.Auth.Domain.Entity;
using B.Auth.Domain.Repository;
using B.Auth.Enum;
using MediatR;

namespace B.Auth.APi.Application.CommandHand.Leaves
{
    public class LeaveShenSaveCommandHand : IRequestHandler<LeaveShenSaveCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<LeaveModel> _leave;
        private readonly IMapper mapper;

        public LeaveShenSaveCommandHand(IBaseRepository<LeaveModel> leave, IMapper mapper)
        {
            _leave = leave;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(LeaveShenSaveCommand request, CancellationToken cancellationToken)
        {

            var result = new ApiResult<int>();


           
            var list=_leave.GetAll().FirstOrDefault(x=>x.Id==request.Id);
            list.AuditStep++;

           
            if (list.AuditStep == list.DepartmentHead.Split(',').Length)
            {
                list.LeaveType = 1;
                list.AuditNowName = "已完成";
               


            }
            else
            {
                list.AuditNowName = list.DepartmentHead.Split(',')[Convert.ToInt64(list.AuditStep)];
            
            
            }
            if (request.LeaveType == 2)
            {
                
                list.AuditNowName = "已完成";
                list.LeaveType = 2;
              

            }
            list.LeaveError = request.LeaveError += request.LeaveError;


            //    var leaves = mapper.Map<LeaveModel>(request);

            list.Status = true;

            if (list.LeaveType == 1)
            {
                list.ShenType = 1;
            }
            if (list.LeaveType == 2)
            {
                list.ShenType = 2;
            }
            _leave.Update(list);

            result.Message = "审批完成";
            result.Code = ApiEnum.ok;

            return Task.FromResult(result); 
            


        }
    }
}
